import * as THREE from 'three';
import { initScene } from './initScene.ts';
import GUI from "three/examples/jsm/libs/lil-gui.module.min.js";
import { DemoManager, FireworksDemo, FountainDemo, FlameDemo } from './demos/index';

const stage = initScene({
    cameraPosition:new THREE.Vector3(
      -73.42797021219732, 69.63469049102542, 99.22670047742687),    
})

  // 获取3D容器中的场景、相机、渲染器、控制器和DOM元素
  const { scene, camera, renderer, controls } = stage;
  renderer.domElement.classList.add('three')
  controls.target.set(16.71312679560799, 19.29706388527522, 50.51018076341377)
  controls.update()
  // 创建GUI
  const gui = new GUI();
  
  // 创建Demo管理器
  const demoManager = new DemoManager(scene, gui);
  
  // 注册所有demo
  demoManager.registerDemo(new FireworksDemo(scene));
  demoManager.registerDemo(new FountainDemo(scene));
  demoManager.registerDemo(new FlameDemo(scene));
  
  // 定义返回值，包含3D容器和GUI
  const res = {
    stage,
    gui,
    demoManager
  }
  renderer.domElement.addEventListener("dblclick", ((e)=>{
    console.log(e.clientX, e.clientY,e.offsetX,e.offsetY)
    const rect = renderer.domElement.getBoundingClientRect();
    const x = (e.clientX - rect.left) / rect.width;
    const y = (e.clientY - rect.top) / rect.height;
    console.log(x, y)
    console.log({camera: camera.position.toArray(),target: controls.target.toArray()})
  }))


  // 创建网格
  const grid =new  THREE.GridHelper(100, 50, 0x888888, 0x444444);
  // 创建坐标轴
  const axes = new THREE.AxesHelper(100);
  // 将网格和坐标轴添加到场景中
  scene.add(axes,grid);

  const clock = new THREE.Clock();
  
  // FPS统计
  let lastTime = 0;
  let frameCount = 0;
  
  // 键盘事件监听
  window.addEventListener('keydown', function (event) {
    switch (event.key) {
      case 'r':
        // 按R键重置当前emo
        const currentDemo = demoManager.getCurrentDemo();
        if (currentDemo) {
          currentDemo.reset();
        }
        break;
      default:
        break; 
    }
  });

  // 将GUI选项添加到GUI中
  stage.beforeRender= ()=>{
    const delta = clock.getDelta();
    
    // 更新demo管理器
    demoManager.update(delta);
    
    // 更新FPS统计
    frameCount++;
    const currentTime = performance.now();
    if (currentTime - lastTime >= 1000) {
      const fps = frameCount / ((currentTime - lastTime) / 1000);
      demoManager.setFPS(fps);
      frameCount = 0;
      lastTime = currentTime;
    }
  }

  stage.loopRender()
  
  document.body.append(renderer.domElement)
  
  stage.resize()

